<?php

namespace App\Http\Controllers\API\Auth;

use App\Admin\Repositories\CarPackageOrder;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Services\LifeCycle\WechatService;
use EasyWeChat\Factory;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;

class LoginController extends Controller
{

    public function login(Request $request)
    {
        if (isLocalHost()) {
            $user = User::find(env('LOCAL_USER_ID'));
        } else {
            $param = $request->all();
            $code = $param['code'];
            $rawData = $param['rawData'];

            $app = Factory::miniProgram(config('wechat.mini_program.default'));
            $data = $app->auth->session($code);

            //判断code是否过期
            if (isset($data['errcode'])) {
                return $this->failure('token过期或不正确！', ['code' => 401]);
            }

            $open_id = $data['openid'];
            $union_id = $data['unionid'];
            $session_key = $data['session_key'];
            $user_data = json_decode($rawData, true);

            $user = User::where('union_id', $union_id)->first();

            if (!$user) {
                $user = User::create([
                    'nickname' => $user_data['nickName'],
                    'avatar' => $user_data['avatarUrl'],
                    'app_open_id' => $open_id,
                    'union_id' => $union_id
                ]);
            }
        }

        return $this->success($this->createTokenUser($user));
    }

    /**
     * 登录后返回
     * @param User $user
     * @return mixed
     */
    protected function createTokenUser(User $user)
    {
        $success['token_type'] = 'Bearer';
        $success['token'] =  $user->createToken('MyApp')->accessToken;
        $success['user_phone'] =  $user->phone;
        $success['user_type'] =  $user->type;
        $success['package_attr_permission_ids'] = $user->package_attr_permission_ids;

        return $success;
    }

    /**
     * 退出登录
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        $user = Auth::user();

        if (empty($user)) {
            return $this->apiReturn($user, '暂未登录', false);
        }

        // 获取当前登陆用户的token并且将其删除
        $token = Auth::guard('api')->user()->token();

        if (empty($token)) {
            return $this->failure('暂无有效令牌');
        }

        if (!empty($token->delete())) {
            return $this->success([], '退出成功');
        } else {
            return $this->failure('token删除失败');
        }
    }
}
